<?php

namespace App\ClickHouse;

use App\ClickHouse\Models\Reports;
use App\Services\ServiceBase;

class AdCostService extends ServiceBase
{
    public function getTodayCost($params)
    {
        $stime = $params['stime'];
        $etime = $params['etime'];
        $plan_id = $params['plan_id'];

        $wheres = [];
        $wheres[] = "`#create_time` >= {$stime}";
        $wheres[] = "`#create_time` < {$etime}";
        $wheres[] = "plan_id = {$plan_id}";

        foreach (['myad_group_id', 'myad_ad_id'] as $key) {
            if (isset($params[$key])) {
                $val = $params[$key];
                $wheres[] = "{$key} = {$val}";
            }
        }
        $wherestr = implode(' AND ', $wheres);

        $sql = "
            SELECT sum(cost) as cost FROM reports FINAL
            WHERE {$wherestr}
            AND `#report_type` = 1001
        ";

        $allcost = 0;
        $stat  = Reports::getInstance()->select($sql);
        $data  = $stat->rows();
        foreach ($data as $val) {
            $allcost += $val['cost'];
        }

        // yqlog($sql);

        return $allcost;
    }
}
